package com.njupt.StringProblem;

/**
 * leetcode 28. 找出字符串中第一个匹配项的下标
 */
public class StrStr {

    /**
     * 暴力解法：haystack设置一个起始下标startIndex，表示每次开始比较的位置，
     *      和needle中每一个字符比较，相等就各++
     *      needle中的个字符下标越界返回startIndex
     *
     *      不然的话needle下标初始为0，haystack下标为startIndex下一个位置
     * @param haystack
     * @param needle
     * @return
     */
    public int strStr(String haystack, String needle) {
        int startIndex = 0;
        int hayIterTime = haystack.length()-needle.length();

        int hayIndex = 0;
        int needleIndex = 0;
        while(true){

            hayIndex = startIndex;
            while(haystack.charAt(hayIndex) == needle.charAt(needleIndex)){
                hayIndex++;
                needleIndex ++;

                if(needleIndex == needle.length()){
                    return startIndex;
                }
            }

            needleIndex = 0;
            startIndex++;

            if(startIndex>hayIterTime){
                return -1;
            }
        }
    }

    public int strStr1(String haystack, String needle){
        int nLen = needle.length();
        int startIndex = 0;
        while(haystack.length()>=nLen){
            if(haystack.startsWith(needle)){
                return startIndex;
            }
            startIndex ++;
            haystack = haystack.substring(1,haystack.length());
        }
        return -1;

    }

    public static void main(String[] args) {
        String haystack = "leetcode";
        String needle = "leeto";
        StrStr test = new StrStr();
        System.out.println(test.strStr1(haystack, needle));
    }
}
